package cn.yj.common.config;

import cn.yj.entity.R;
import cn.yj.params.check.ParamsIsNullException;
import cn.yj.tools.exception.AbstractExceptionHandler;
import cn.yj.tools.exception.Error;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.ws.rs.NotFoundException;

/**
 * <br>
 *
 * @author 永健
 * @since 2020-11-29 18:07
 */
@Configuration
@RestControllerAdvice
public class GlobError extends AbstractExceptionHandler {

    @ExceptionHandler(UnauthorizedException.class)
    public R handleException(UnauthorizedException e) {
        return executeError(Error.权限异常.getCode(), "操作权限不足,请联系管理员",e);
    }

    @ExceptionHandler(ParamsIsNullException.class)
    public R handleException(ParamsIsNullException e) {
        return executeError(Error.参数异常.getCode(), e.getMessage(),e);
    }

    @ExceptionHandler(UnauthenticatedException.class)
    public R handleException(UnauthenticatedException e) {
        return executeError(Error.未登陆异常.getCode(), "用户未登陆/匿名访问",e);
    }

    @ExceptionHandler(NotFoundException.class)
    public R NotFoundException(NotFoundException e) {
        return executeError(Error.请求路径异常.getCode(), Error.请求路径异常.getErrMsg()+"[ "+e.getMessage()+" ]",e);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public R NoHandlerFoundException(NoHandlerFoundException e) {
        return executeError(Error.请求路径异常.getCode(), Error.请求路径异常.getErrMsg()+"[ "+e.getRequestURL()+" ]",e);
    }


    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public R maxUploadSizeExceededException(MaxUploadSizeExceededException e) {
        return executeError(R.ERROR_CODE,e.getLocalizedMessage(),e);
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public R IllegalArgumentException(IllegalArgumentException e) {
        return executeError(Error.参数异常.getCode(),"请求参数有误:" + e.getMessage(),e);
    }

}
